﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using ECatalog.Models;
using ECatalog.Models.Structures;
using ECatalog.Models.UserModel;

namespace ECatalog.Controllers
{
    [Authorize]
    public class StructureController : Controller
    {
        private readonly IStructureRepository structureRepository;
        private readonly IUserRepository userRepository;

        public StructureController(IStructureRepository structureRepository, IUserRepository userRepository)
        {
            this.structureRepository = structureRepository;
            this.userRepository = userRepository;
        }

        [Authorize]
        [HttpPost]
        public PartialViewResult Add(Structure structure)
        {
            @ViewBag.IsAdmin = userRepository.IsAdmin(User.Identity.Name);
            if (Request.IsAjaxRequest())
            {
                if (string.IsNullOrWhiteSpace(structure.Value) || string.IsNullOrWhiteSpace(structure.Name))
                {
                    return PartialView(); 
                }
                structure = structureRepository.Add(structure);               
                return PartialView("StructureItem", structure);
            }
            return PartialView();
        }

        [Authorize]
        public JsonResult Remove(int structureid)
        {
            @ViewBag.IsAdmin = userRepository.IsAdmin(User.Identity.Name);
            if (Request.IsAjaxRequest())
            {
                structureRepository.Remove(structureid);
                return Json("ok");
            }
            return Json("error");
        }
    }
}
